﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.UserModel;

namespace Office
{
    public class WordHelper : WordInterface
    {
        XWPFDocument WordObject = new XWPFDocument();

        public void LoadWord(ulong width = 11906, ulong height = 16838, ulong left = 500, ulong right = 500, string top = "550", string bottom = "550")
        {
            WordObject = new XWPFDocument();
            //实例一个尺寸类的实例
            CT_SectPr m_SectPr = new CT_SectPr();
            m_SectPr.pgSz.w = width;//设置宽度（这里是一个ulong类型）
            m_SectPr.pgSz.h = height;//设置高度（这里是一个ulong类型）
            m_SectPr.pgMar.left = left;//左边距
            m_SectPr.pgMar.right = right;//右边距
            m_SectPr.pgMar.top = top;//_ 上边距
            m_SectPr.pgMar.bottom = bottom;// 下边距
            WordObject.Document.body.sectPr = m_SectPr;//设置页面的尺寸
        }
        public void AddText(string value, int fontsize = 10, string foreground = "#5F6368", int spacingBeforeLines = 10, int SpacingAfterLines = 10,
            string fontFanmily = "微软雅黑", FontCharRange fontCharRange = FontCharRange.None, bool isBold = false,
            int indentationFirstLine = 500, ParagraphAlignment paragraphAlignment = ParagraphAlignment.LEFT)
        {
            //添加段落
            var paragraph = WordObject.CreateParagraph();
            var run = paragraph.CreateRun();
            run.FontSize = fontsize;//字体大小
            run.SetColor(foreground);
            paragraph.SpacingBeforeLines = spacingBeforeLines; //上方距离
            paragraph.SpacingAfterLines = SpacingAfterLines;//下方距离
            run.SetFontFamily(fontFanmily, fontCharRange);//设置字体
            run.IsBold = isBold;
            paragraph.IndentationFirstLine = indentationFirstLine; //首行缩进程度
            paragraph.Alignment = paragraphAlignment; //字体居向
            run.SetText(value);
        }

        public void AddDataTable(DataTable dataTable)
        {
            //获取datatable的列名
            string[] ColumnsName = GetColumnsByDataTable(dataTable);
            //获取列和行数
            int RowCount = dataTable.Rows.Count;
            int ColCount = dataTable.Columns.Count;
            //创建可容纳datatable的表
            XWPFTable table = WordObject.CreateTable(RowCount + 1, ColCount);
            //设置列宽
            table.Width = 5000;
            var paragraph = WordObject.CreateParagraph();
            var run = paragraph.CreateRun();
            //设置第一行
            for (int j = 0; j < ColCount; j++)
            {
                CT_P para = new CT_P();
                paragraph = new XWPFParagraph(para, table.Body);
                paragraph.Alignment = ParagraphAlignment.CENTER;
                run = paragraph.CreateRun();
                run.FontFamily = "微软雅黑";
                run.FontSize = 12;
                run.IsBold = true;
                run.SetText(ColumnsName[j]);
                //第一行颜色设置深一点
                table.GetRow(0).GetCell(j).SetColor("#E7EAED");
                table.GetRow(0).GetCell(j).SetParagraph(paragraph);
            }
            //继续添加参数
            for (int i = 0; i < RowCount; i++)
            {
                for (int j = 0; j < ColCount; j++)
                {
                    CT_P para = new CT_P();
                    paragraph = new XWPFParagraph(para, table.Body);
                    paragraph.Alignment = ParagraphAlignment.CENTER;
                    run = paragraph.CreateRun();
                    run.FontFamily = "微软雅黑";
                    run.FontSize = 12;
                    run.IsBold = false;
                    run.SetText(dataTable.Rows[i][ColumnsName[j]].ToString());
                    table.GetRow(i + 1).GetCell(j).SetParagraph(paragraph);
                }
            }
        }
        private string[] GetColumnsByDataTable(DataTable dt)
        {
            string[] strColumns = null;
            if (dt.Columns.Count > 0)
            {
                int columnNum = 0;
                columnNum = dt.Columns.Count;
                strColumns = new string[columnNum];
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    strColumns[i] = dt.Columns[i].ColumnName;
                }
            }
            return strColumns;
        }


        public void SaveWord(string path, string wordName)
        {


            string fullname = (path.Replace(@"\", "/") + "/").Replace("//", "/") + wordName.Replace(".docx", "") + ".docx";

            //如果文件夹不存在就创建
            System.IO.FileInfo fi = new System.IO.FileInfo(fullname);
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }

            FileStream fs = new FileStream(fullname, FileMode.OpenOrCreate);
            WordObject.Write(fs);
        }
        public void SaveWord(string fullname)
        {


            //如果文件夹不存在就创建
            System.IO.FileInfo fi = new System.IO.FileInfo(fullname);
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }

            FileStream fs = new FileStream(fullname, FileMode.OpenOrCreate);
            WordObject.Write(fs);
        }
    }

    interface WordInterface
    {
        /// <summary>
        /// 初始化一个Word
        /// </summary>
        /// <param name="width">纸张宽度</param>
        /// <param name="height">纸张高度</param>
        /// <param name="left">左边距</param>
        /// <param name="right">右边距</param>
        /// <param name="top">上边距</param>
        /// <param name="bottom">下边界</param>
        void LoadWord(ulong width, ulong height, ulong left, ulong right, string top, string bottom);

        /// <summary>
        /// 添加段落
        /// </summary>
        /// <param name="value">段落文本</param>
        /// <param name="fontsize">字体大小</param>
        /// <param name="foreground">字体颜色</param>
        /// <param name="spacingBeforeLines">段前距离</param>
        /// <param name="SpacingAfterLines">段后距离</param>
        /// <param name="fontFanmily">字体</param>
        /// <param name="fontCharRange">编码类型</param>
        /// <param name="isBold">是否加粗</param>
        /// <param name="indentationFirstLine">首行缩进</param>
        /// <param name="paragraphAlignment">段落偏向</param>
        void AddText(string value, int fontsize, string foreground, int spacingBeforeLines, int SpacingAfterLines,
            string fontFanmily, FontCharRange fontCharRange, bool isBold,
            int indentationFirstLine, ParagraphAlignment paragraphAlignment);

        /// <summary>
        /// 添加表格
        /// </summary>
        /// <param name="dt">需要添加的表格数据</param>
        void AddDataTable(DataTable dt);

        /// <summary>
        /// 保存Word
        /// </summary>
        /// <param name="path">保存路径</param>
        /// <param name="wordName">word文件名</param>
        void SaveWord(string path,string wordName);
    }
}
